package com.luxx.util;

import org.springframework.util.DigestUtils;

import java.io.UnsupportedEncodingException;
import java.util.*;


public class MD5 {

    private final static String DEFAULT_ENCODING = "UTF-8";
    
    // 全局数组
    private final static String[] strDigits = { "0", "1", "2", "3", "4", "5",
            "6", "7", "8", "9", "a", "b", "c", "d", "e", "f" };
    /**
     * 签名字符串
     * @param text 需要签名的字符串
     * @param key 密钥
     * @param input_charset 编码格式
     * @return 签名结果
     */
    public static String sign(String text, String key, String input_charset) {
    	text = text + key;
        return DigestUtils.md5DigestAsHex(getContentBytes(text, input_charset));
    }

    public static String sign(String text, String key) {
        return sign(text, key, DEFAULT_ENCODING);
    }
    public static String sign(String text) {
        return sign(text, "", DEFAULT_ENCODING);
    }

    /**
     * 签名字符串
     * @param text 需要签名的字符串
     * @param sign 签名结果
     * @param key 密钥
     * @param input_charset 编码格式
     * @return 签名结果
     */
    public static boolean verify(String text, String sign, String key, String input_charset) {
    	text = text + key;
    	String mysign = DigestUtils.md5DigestAsHex(getContentBytes(text, input_charset));
    	if(mysign.equals(sign)) {
    		return true;
    	}
    	else {
    		return false;
    	}
    }

    public static boolean verify(String text, String sign, String key) {
        return verify(text, sign, key, DEFAULT_ENCODING);
    }

    /**
     * @param content
     * @param charset
     * @return
     * @throws java.security.SignatureException
     * @throws UnsupportedEncodingException
     */
    private static byte[] getContentBytes(String content, String charset) {
        if (charset == null || "".equals(charset)) {
            return content.getBytes();
        }
        try {
            return content.getBytes(charset);
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException("MD5签名过程中出现错误,指定的编码集不对,您目前指定的编码集是:" + charset);
        }
    }

    public static void main(String[] arg) {
        System.out.println(sign("datetime=20151125164530&msisdn=18812345678&prodCode=30005&uid=jinjukeji", "123456789"));
    }




    // 返回形式为数字跟字符
    private static String byteToArrayString(byte bByte) {
        int iRet = bByte;
        if (iRet < 0) {
            iRet += 256;
        }
        int iD1 = iRet / 16;
        int iD2 = iRet % 16;
        return strDigits[iD1] + strDigits[iD2];
    }

    // 返回形式只为数字
    @SuppressWarnings("unused")
	private static String byteToNum(byte bByte) {
        int iRet = bByte;
        if (iRet < 0) {
            iRet += 256;
        }
        return String.valueOf(iRet);
    }

    // 转换字节数组 16进制字串
    private static String byteToString(byte[] bByte) {
        StringBuilder sBuffer = new StringBuilder();
        for (int i = 0; i < bByte.length; i++) {
            sBuffer.append(byteToArrayString(bByte[i]));
        }
        return sBuffer.toString();
    }

    /**
     * 把数组所有元素排序，并按照“参数=参数值”的模式用“&”字符拼接成字符串
     * @param params 需要排序并参与字符拼接的参数组
     * @return 拼接后字符串
     */
    public static String createLinkString(Map<String, String> params, String... ignores) {
        List<String> ignore = new ArrayList<>();
        if (ignores.length > 0) {
            ignore = Arrays.asList(ignores);
        }
        List<String> keys = new ArrayList<>(params.keySet());
        Collections.sort(keys);

        StringBuffer prestr = new StringBuffer();

        for (int i = 0; i < keys.size(); i++) {
            String key = keys.get(i);
            if (ignore.contains(key)) {
                continue;
            }
            String value = params.get(key);

            if (value == null || value.trim().length() == 0) {
                continue;
            }

            if (i == keys.size() - 1) {//拼接时，不包括最后一个&字符
                prestr.append(key).append("=").append(value);
            } else {
                prestr.append(key).append("=").append(value).append("&");
            }
        }
        String s = prestr.toString();
        if (s.endsWith("&")) {
            s = s.substring(0, s.length() - 1);
        }

        return s;
    }

    public static String sign(Map<String, String> sPara, String key) {
        String prestr = createLinkString(sPara, "sign"); //把数组所有元素，按照“参数=参数值”的模式用“&”字符拼接成字符串
        String mysign = sign(prestr, key);
        return mysign;
    }
    public static boolean verify(Map<String, String> sPara, String key, String sign) {
        String mysign = sign(sPara, key);
        return mysign.equals(sign);
    }

}